package ar.edu.caece.compiler.helpers;

import static ar.edu.caece.compiler.helpers.FileLocator.getPath;
import static org.apache.commons.logging.LogFactory.getLog;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;

public class Helper {

	public final static String DEFAULT_ENCONDING = "UTF-8";
	
	private final static String COMMENT = "#";	
	
	private static Log logger = getLog(Helper.class);

	public static List<String> load(String file) throws IOException {
		
		List<String> values = new ArrayList<String>();
		BufferedReader br = null;
		String line;
		
		try {
			br = new BufferedReader(new FileReader(getPath(file, DEFAULT_ENCONDING)));
			while((line = br.readLine()) != null) {
				if(line.isEmpty() | line.startsWith(COMMENT))
					continue;
				values.add(line);
			}
			return values;
		}	
		finally {		
			close(br);
		}	
	}	
	
	public static void writeFile(String fileName,String content) throws IOException {
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(fileName));
			
			writer.write(content);
		} finally {
			if(writer!=null) writer.close();
		}
	}
	
	public static void close(BufferedReader br) {
		try {
			if (br != null)
				br.close();
		} catch (IOException e) {
			logger.error("Error al cerrar el archivo", e);
		}			
	}
}
